/**
 * Copyright (C) 2010  Johan Basson
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

package symorg.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

/**
 * Basic Logging to text file.
 * 
 * @author johan
 */
public class Logger {

    private FileConnection con;
    private OutputStream out;

    public Logger(String file) throws IOException {
         con = (FileConnection) Connector.open(file);
         if (!con.exists()) {
             con.create();
         }
         out = con.openOutputStream(con.fileSize());
    }

    private String createMessage(String level, String msg) {
        Date d = new Date();
        StringBuffer sb = new StringBuffer();
        sb.append(d.toString());
        sb.append(" ");
        sb.append(level);
        sb.append(" ");
        sb.append(msg);
        sb.append("\n\r");
        return sb.toString();
    }

    public void debug(String message) {
        try {
            out.write(createMessage("DEBUG", message).getBytes());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public void info(String message) {
        try {
            out.write(createMessage("INFO", message).getBytes());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public void error(String message)  {
        try {
            out.write(createMessage("ERROR", message).getBytes());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public void error(String message, Exception e)  {
        try {
            out.write(createMessage("ERROR", message).getBytes());
            out.write(e.toString().getBytes());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public void close() {
        try {
            out.close();
            con.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
